package com.xuxingcan.wifiadb;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.text);
        findViewById(R.id.wifi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Runtime.getRuntime().exec("su");
                    Runtime.getRuntime().exec("setprop service.adb.tcp.port 5555");
                    Runtime.getRuntime().exec("stop adbd");
                    Runtime.getRuntime().exec("start adbd");
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    mTextView.setText("设置WIFI成功,当前WIFI地址：\n" + intToIp(wifiManager.getConnectionInfo().getIpAddress()));
                } catch (Exception e) {
                    e.printStackTrace();
                    mTextView.setText("错误:" + e.getMessage());
                }
            }
        });
        findViewById(R.id.usb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Runtime.getRuntime().exec("su");
                    Runtime.getRuntime().exec("setprop service.adb.tcp.port -1");
                    Runtime.getRuntime().exec("stop adbd");
                    Runtime.getRuntime().exec("start adbd");
                    mTextView.setText("设置USB成功!");
                } catch (IOException e) {
                    e.printStackTrace();
                    mTextView.setText("错误:" + e.getMessage());
                }
            }
        });
    }

    public String intToIp(int i) {
//        return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }

    public static void exeShell(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                Log.i("exeShell", line);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
